package org.ndx.majick.ui.object;

import javax.swing.JComponent;

import org.ndx.majick.properties.Property;
import org.ndx.majick.ui.IClassUIProvider;
import org.ndx.majick.ui.IPropertyUIMetadata;
import org.ndx.majick.ui.UIProvider;

/**
 * Contrary to parent class, this one tries harder to find both viewer and editor by relying upon dynamic property type.
 * This is obviously not the best idea, but it can save huge amount of time.
 * @author Nicolas Delsaux
 *
 */
public class DynamicObjectUIProvider extends ObjectUIProvider implements
		IClassUIProvider {

	private UIProvider provider;

	public DynamicObjectUIProvider(UIProvider provider) {
		this.provider = provider;
	}

	@Override
	public JComponent getEditor(IPropertyUIMetadata metadata, Property<?> source) {
		IClassUIProvider uiProvider = locateProvider(source);
		if(uiProvider==this)
			return super.getEditor(metadata, source);
		else
			return uiProvider.getEditor(metadata, source);
	}
	
	/**
	 * Locate provider by calling inner methods of provider
	 * @param source property to edit
	 * @return this if none was found, or a usable provider
	 */
	IClassUIProvider locateProvider(Property<?> source) {
		return provider.locateProvider(source.get().getClass());
	}

	@Override
	public JComponent getViewer(IPropertyUIMetadata metadata, Property<?> source) {
		IClassUIProvider uiProvider = locateProvider(source);
		if(uiProvider==this)
			return super.getViewer(metadata, source);
		else
			return uiProvider.getViewer(metadata, source);
	}
}
